package com.sj.parksdk.fragment.pay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.ruffian.library.widget.RLinearLayout;
import com.ruffian.library.widget.RTextView;
import com.sj.parksdk.R;
import com.sj.parksdk.R2;
import com.sj.parksdk.adapter.base.delegate.SimpleDelegateAdapter;
import com.sj.parksdk.adapter.pay.AdapterExpandableListPurchase;
import com.sj.parksdk.core.BaseFragment;
import com.sj.parksdk.core.http.subscriber.TipRequestSubscriber;
import com.sj.parksdk.fragment.carmanage.FragmentParkingPay;
import com.sj.parksdk.net.http.ApiHelper;
import com.sj.parksdk.net.http.MyNetApi;
import com.sj.parksdk.net.http.callback.TipRequestCallBack;
import com.sj.parksdk.net.manager.TokenManager;
import com.sj.parksdk.net.request.MGetRequest;
import com.sj.parksdk.net.result.databean.Data_Car;
import com.sj.parksdk.net.result.databean.Data_PackageOrder;
import com.sj.parksdk.net.result.databean.Data_Purchase;
import com.sj.parksdk.net.result.databean.Data_Weipay_Native;
import com.sj.parksdk.setting.Constans;
import com.sj.parksdk.setting.Dictionary;
import com.sj.parksdk.setting.Extras;
import com.sj.parksdk.utils.Utils;
import com.sj.parksdk.utils.XToastUtils;
import com.sj.parksdk.widget.sweetalert.SweetAlertDialog;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xhttp2.request.CustomRequest;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xrouter.annotation.AutoWired;
import com.xuexiang.xrouter.launcher.XRouter;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.DensityUtils;
import com.xuexiang.xui.utils.ResUtils;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.statelayout.CustomStateOptions;
import com.xuexiang.xui.widget.statelayout.StatefulLayout;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;
import com.xuexiang.xutil.tip.ToastUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Page(name = " 套餐购买 ", params = {Extras.PARK_ID, Extras.PARK_NAME, Extras.PARK_ADDRESS,Extras.BASE_TYPE})
public class FragmentPurchasePlanConfirm extends BaseFragment {
    @BindView(R2.id.tv_park_name)
    TextView tvParkName;
    @BindView(R2.id.tv_park_address)
    TextView tvParkAddress;
    @BindView(R2.id.tv_car_number)
    TextView tvCarNumber;
    @BindView(R2.id.rtv_car_color)
    RTextView rtvCarColor;
    @BindView(R2.id.rll_car_color)
    RLinearLayout rllCarColor;
    @BindView(R2.id.tv_purchase_count)
    TextView tvPurchaseCount;
    @BindView(R2.id.ll_state)
    StatefulLayout llState;
    @BindView(R2.id.recycler_purchase)
    RecyclerView recyclerPurchase;
    @BindView(R2.id.tv_notice)
    TextView tvNotice;
    @BindView(R2.id.bt_next)
    SuperButton btNext;

    private AdapterExpandableListPurchase adapterPurchase;

    @AutoWired(name = Extras.PARK_ID)
    long parkId;
    @AutoWired(name = Extras.PARK_NAME)
    String parkName;
    @AutoWired(name = Extras.PARK_ADDRESS)
    String parkAddress;
    @AutoWired(name = Extras.BASE_TYPE)
    boolean fromMain;

    private Data_Car mCar;

    @Override
    protected int getLayoutId() {
        return R.layout.parksdk_fragment_purchase_plan_confirm;
    }

    @Override
    protected void initArgs() {
        XRouter.getInstance().inject(this);
    }

    @Override
    protected void initViews() {
        initParkInfo();
        initDefaultCar();
        initAdapters();
        queryPackage();
    }

    private void initDefaultCar() {
        mCar = TokenManager.getInstance().getDefaultCar();
        if (mCar == null) {
            rtvCarColor.setVisibility(View.GONE);
            rllCarColor.setVisibility(View.GONE);
            return;
        }
        initCarInfor();
    }

    private void initAdapters() {
        WidgetUtils.initRecyclerView(recyclerPurchase, 0);
        adapterPurchase = new AdapterExpandableListPurchase(recyclerPurchase);
        recyclerPurchase.setAdapter(adapterPurchase);
    }

    private void initParkInfo() {
        tvParkName.setText(parkName);
        tvParkAddress.setText(parkAddress);
    }

    private void initCarInfor() {
        rtvCarColor.setVisibility(View.VISIBLE);
        rllCarColor.setVisibility(View.VISIBLE);
        tvCarNumber.setText(mCar.getCarNo());
        int color = StringUtils.isEmpty(mCar.getPlateColor()) ?
                ResUtils.getColor(Dictionary.Car.PlateColor.PalteColorMap.get(Dictionary.Car.PlateColor.Blue)) :
                ResUtils.getColor(Dictionary.Car.PlateColor.PalteColorMap.get(mCar.getPlateColor()));
        rtvCarColor.setText(StringUtils.isEmpty(mCar.getPlateColor()) ?
                Dictionary.Car.PlateColor.PlateColorNameMap.get(Dictionary.Car.PlateColor.Blue) :
                Dictionary.Car.PlateColor.PlateColorNameMap.get(mCar.getPlateColor()));
        rtvCarColor.getHelper().setBackgroundColorNormal(color);
        rtvCarColor.getHelper().setTextColorNormal(ResUtils.getColor(Dictionary.Car.PlateColor.White.equals(mCar.getPlateColor()) ? R.color.color_3 : R.color.color_white));
        rtvCarColor.getHelper().setBorderWidthNormal(DensityUtils.dp2px(Dictionary.Car.PlateColor.White.equals(mCar.getPlateColor())?1:0));
        rllCarColor.getHelper().setBorderColorNormal(Dictionary.Car.PlateColor.White.equals(mCar.getPlateColor()) ?ResUtils.getColor(R.color.color_3):color);
    }

    @Override
    protected void initListeners() {
        initNoticeClickListener();
    }

    private void initNoticeClickListener() {
        tvNotice.setText(getPrivacyContent(getContext()));
        tvNotice.setMovementMethod(LinkMovementMethod.getInstance());
    }

    /**
     * @return 购买须知
     */
    private static SpannableStringBuilder getPrivacyContent(Context context) {
        SpannableStringBuilder stringBuilder = new SpannableStringBuilder()
                .append("*请认真阅读并同意").append(getUserPrivacyLink(context, ResUtils.getString(R.string.pay_buy_notice), Constans.API_AGREEMENT))
                .append("后再确认支付");
        return stringBuilder;
    }

    /**
     * @return
     */
    private static SpannableString getUserPrivacyLink(Context context, String privacyName, String privacyUrl) {
        SpannableString spannableString = new SpannableString(privacyName);
        spannableString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(@NonNull View widget) {
                Utils.goWeb(context, privacyUrl);
            }

//            @Override
//            public void updateDrawState(@NonNull TextPaint ds) {
//                super.updateDrawState(ds);
//                ds.setUnderlineText(false);
//            }
        }, 0, privacyName.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannableString;
    }

    @OnClick({R2.id.rtv_change_park, R2.id.rtv_change_car, R2.id.tv_buy_record, R2.id.bt_next})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.rtv_change_park) {
            if (fromMain) openPage(FragmentPurchasePlan.class, false);
            else popToBack();
        } else if (id == R.id.rtv_change_car) {
            if (checkLogin())
                openPageForResult(FragmentParkingPay.class, Extras.BASE_IS_SELECTED, Extras.BASE_SELECTED, Extras.REQUEST_CAR_SELECTE_CAR);
        } else if (id == R.id.tv_buy_record) {
            if (checkLogin()) gotoPurchaseBuyRecord(true);
        } else if (id == R.id.bt_next) {
            if (checkData()) {
                confirmPurchaseOrder();
            }
        }
    }

    private boolean checkData() {
        if (mCar == null) {
            ToastUtils.toast("请选择指定车辆");
            return false;
        }
        if (parkId == 0) {
            ToastUtils.toast("请选择指定车场");
            return false;
        }
        if (adapterPurchase.getSelectItem() == null) {
            ToastUtils.toast("请选择指定套餐内容");
            return false;
        }
        if (adapterPurchase.getChildSelectedItem() == null) {
            ToastUtils.toast("请选择指定套餐内容");
            return false;
        }
        return true;
    }

    //确认支付订单信息
    private void confirmPurchaseOrder() {
        String purchaseName = adapterPurchase.getSelectItem().getName();
        List<Data_Purchase.TypeBean> types = adapterPurchase.getSelectItem().getItems();

        String month = adapterPurchase.getChildSelectedItem().getMonth() + "个月";
        String price = "¥" + adapterPurchase.getChildSelectedItem().getMoney();

        String[] dialogStringArray = {mCar.getCarNo() + "(" + Dictionary.Car.PlateColor.PlateColorNameMap.get(mCar.getPlateColor()) + ")" + "\n" + parkName
                , "套餐:" + purchaseName + "\n" + "月数:" + month + "\n" + "价格:" + price};

        SimpleDelegateAdapter adapterDeleteType = newDeleteTypeSelecteAdapter(dialogStringArray);
        LinearLayoutManager lm = new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false);

        new SweetAlertDialog(getContext(), SweetAlertDialog.RECYCLER_TYPE)
                .setTitleText("请确认以下信息")
                .setContentMinHeight(DensityUtils.dp2px(200))
                .setContentText(null)
                .setConfirmText(ResUtils.getString(R.string.dialog_button_goto_pay))
                .setRecyclerAdapter(adapterDeleteType, lm)
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        if (checkLogin()) createPackageOrder(sDialog);
                    }
                })
                .show();

    }

    @SuppressLint("CheckResult")
    private void createPackageOrder(SweetAlertDialog sDialog) {
        sDialog.setTitleGone(true).setContentText(null).setCancelable(false);
        sDialog.changeAlertType(SweetAlertDialog.PROGRESS_TYPE);
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request)
                .packageCreateOrder(mCar.getId(), parkId, adapterPurchase.getSelectItem().getId(), adapterPurchase.getChildSelectedItem().getId()))
                .subscribeWith(new TipRequestSubscriber<Data_PackageOrder>() {
                    @Override
                    protected void onSuccess(Data_PackageOrder data) {
                        weiPay(data,sDialog);
                    }

                    @Override
                    public void onError(ApiException e) {
                        createPackageOrderError(e.getMessage(),sDialog);
                    }
                });
    }

    private void createPackageOrderError(String message, SweetAlertDialog sDialog) {
        sDialog.setContentText(StringUtils.isEmpty(message)?"下单失败,请重新尝试":message)
                .setCancelText(ResUtils.getString(R.string.back))
                .setConfirmText(ResUtils.getString(R.string.OK))
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        sweetAlertDialog.dismiss();
                        popToBack();
                    }
                })
                .setConfirmClickListener(null)
                .changeAlertType(SweetAlertDialog.ERROR_TYPE);
    }

    @SuppressLint("CheckResult")
    private void weiPay(Data_PackageOrder response, SweetAlertDialog sDialog) {
        CustomRequest request = XHttp.custom();
        request.apiCall(ApiHelper.getInstance(request)
                .weipaynative(response.getTradeNo(), response.getTimestamp(), response.getSign()))
                .subscribeWith(new TipRequestSubscriber<Data_Weipay_Native>() {
                    @Override
                    protected void onSuccess(Data_Weipay_Native data) {
                        String weipayurl = data.getCode_url();
                        createQrCode(weipayurl,sDialog);
                    }
                });
    }

    private void createQrCode(String weipayurl,SweetAlertDialog sDialog) {
        if (StringUtils.isEmpty(weipayurl)) {
            XToastUtils.error("二维码内容为空");
            return;
        }
        Bitmap QRcode = XQRCode.createQRCodeWithLogo(weipayurl, 400, 400, null);
        if (QRcode == null) {
            XToastUtils.error("生成二维码失败");
            return;
        }
        sDialog.setCustomImage(new BitmapDrawable(QRcode))
                .setContentText("使用微信扫码支付")
                .setCancelText("取消")
                .setConfirmText("支付完成")
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                    }
                })
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        gotoPurchaseBuyRecord(false);
                    }
                }).changeAlertType(SweetAlertDialog.CUSTOM_IMAGE_TYPE);
    }

    private SimpleDelegateAdapter newDeleteTypeSelecteAdapter(String[] dialogStringArray) {
        return new SimpleDelegateAdapter<String>(R.layout.parksdk_adapter_dilaog_cofirm_purchase, new LinearLayoutHelper(), dialogStringArray) {
            @Override
            protected void bindData(@NonNull RecyclerViewHolder holder, int position, String item) {
                holder.text(R.id.tv_name, item);
                if (position != 0) holder.textColorId(R.id.tv_name, R.color.color_9);
            }
        };
    }

    private void gotoPurchaseBuyRecord(boolean click) {
        if (click) openPage(FragmentPackageRecord.class);
        else openPage(FragmentPackageRecord.class, false);
    }

    private void queryPackage() {
        if (parkId == 0) {
            XToastUtils.warning("未识别到车场");
            return;
        }
        if (mCar == null) {
            XToastUtils.warning("请先指定车辆");
            return;
        }
        if (StringUtils.isEmpty(mCar.getVehicleType())) {
            XToastUtils.warning("车辆类型出错");
            return;
        }
        new MGetRequest(MyNetApi.PACKAGE_PACKAGES + parkId + "/packages")
                .visit()
                .params("vehicleType", mCar.getVehicleType())
                .execute(new TipRequestCallBack<List<Data_Purchase>>() {
                    @Override
                    public void onSuccess(List<Data_Purchase> datas) throws Throwable {
                        if (datas == null) {
                            llState.showCustom(new CustomStateOptions().message("没有合适的套餐" + "\n\n" + "请重新选择停车位置\n\n"));
                            return;
                        }
                        if (datas.size() == 0)llState.showCustom(new CustomStateOptions().message("没有合适的套餐" + "\n\n" + "请重新选择停车位置\n\n"));
                        else llState.showContent();
                        adapterPurchase.refreshData(datas);
                        tvPurchaseCount.setText("(共"+datas.size()+")");
                    }
                    @Override
                    public void onError(ApiException e) {
                        llState.showError(e.getMessage(),null);
                    }
                });
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode != Activity.RESULT_OK) return;
        if (data == null) return;
        if (requestCode == Extras.REQUEST_CAR_SELECTE_CAR) updateCarInfo(data);
    }

    private void updateCarInfo(Intent data) {
        String json = data.getStringExtra(Extras.BASE_JSON);
        if (StringUtils.isEmpty(json)) return;
        Data_Car car = JsonUtil.fromJson(json, Data_Car.class);
        if (car == null) return;
        mCar = car;
        initCarInfor();
        queryPackage();
    }
}
